import fs from 'fs'
import { reflectType } from './mysqlreflect.js'
import { formatToUpHump } from './utils.js'
export const createForm = (columns, tableName) => {
  fs.readFile('src/scripts/config.json', 'utf8', (err, data) => {
    if (err) throw err
    const config = JSON.parse(data)
    const folder = `${config.vendorFolder}/${tableName}`
    // verify file is exist or not
    const fileName = `${folder}/form.ts`

    if (fs.existsSync(fileName)) {
      // file is exist
      console.log(`======file is existed and ignored to created form:${tableName}=======`)
    } else {
      // file is not exist
      if (!fs.existsSync(folder)) {
        fs.mkdirSync(folder, { recursive: true }, (err) => {
          if (err) throw err
        })
      }
      const fields = []
      const model = []
      let arr = []
      for (const i in columns) {
        const type = reflectType(columns[i])
        fields.push(`${formatToUpHump(columns[i].columnName)}:${type}`)
        switch (type) {
          case 'number':
            if (columns[i].columnDefault !== null) {
              model.push(`${formatToUpHump(columns[i].columnName)}:${Number(columns[i].columnDefault)}`)
            } else {
              model.push(`${formatToUpHump(columns[i].columnName)}:0`)
            }

            break
          case 'String':
            if (columns[i].columnDefault !== null) {
              model.push(`${formatToUpHump(columns[i].columnName)}:'${(columns[i].columnDefault)}'`)
            } else {
              model.push(`${formatToUpHump(columns[i].columnName)}:''`)
            }

            break
          case 'Array<String>':
            if (columns[i].columnDefault !== null) {
              arr = columns[i].columnDefault.split(',')
            }
            model.push(`${formatToUpHump(columns[i].columnName)}:${JSON.stringify(arr)}`)

            break
        }
      }
      const content = `export interface Form{\n\t${fields.join(',\n\t')}\n}\nexport const model:Form = {\n\t${model.join(',\n\t')}\n}`
      fs.writeFileSync(fileName, content, { flag: 'a' }, (err) => {
        if (err) {
          console.log('========error======')
          throw err
        } else {
          console.log(`======succeessfully created form:${tableName}=======`)
        }
      })
    }
  })
}
